package com.badshun.apkextractor;

import android.app.*;
import android.view.*;
import android.os.*;
import android.content.pm.*;
import android.widget.*;
import android.content.*;
import java.util.*;
import android.graphics.drawable.*;
import android.widget.AdapterView.*;
import java.io.*;
import java.nio.file.*;

public class SystemAppFragment extends Fragment {
	private List<PackageInfo> infos;
	private List<Drawable> drawables;
	private List<String> appNames;
	private List<String> packageNames;
	private List<String> sourceDirs;
	
	private Context context;
	
	private String path;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.system, container, false);
		
		context = getContext();
		
		PackageManager pm = getContext().getPackageManager();
		
		path = Environment.getExternalStorageDirectory().getPath();

		infos = pm.getInstalledPackages(0);
		drawables = new ArrayList<Drawable>();
		appNames = new ArrayList<String>();
		packageNames = new ArrayList<String>();
		sourceDirs = new ArrayList<String>();

		for(int i = 0; i < infos.size(); i++) {
			if((infos.get(i).applicationInfo.flags & infos.get(i).applicationInfo.FLAG_SYSTEM) <= 0) {
				infos.remove(i);
				i = i - 1;
			} else {
				String packageName = infos.get(i).packageName;
				String appName = (String) infos.get(i).applicationInfo.loadLabel(pm);
				String appApkPath = infos.get(i).applicationInfo.sourceDir;
				Drawable icon = infos.get(i).applicationInfo.loadIcon(pm);

				drawables.add(icon);
				appNames.add(appName);
				sourceDirs.add(appApkPath);
				packageNames.add(packageName);
			}
		}

		ListView listview = view.findViewById(R.id.system_lv);
		listview.setAdapter(new BadAdapter(getContext()));
		
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> p1, View p2, final int p3, long p4) {
				AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
				builder
					.setTitle(appNames.get(p3))
					.setIcon(drawables.get(p3))
					.setMessage("是否要提取该应用？")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface p1, int p2) {
							final EditText edit = new EditText(getContext());
							edit.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
							edit.setText(path + "/ApkExtractor/");
							
							AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
							builder
								.setTitle("设置提取路径")
								.setView(edit)
								.setPositiveButton("确定", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface p1, int p2) {
										final ProgressDialog pDialog = new ProgressDialog(context);
										pDialog.setCanceledOnTouchOutside(false);
										pDialog.setMessage("正在提取...");
										pDialog.show();
										
										final Handler handler = new Handler() {
											@Override
											public void handleMessage(Message msg) {
												if(msg.obj == "FINISH") {
													pDialog.dismiss();
													Toast.makeText(context, "提取完成", 0).show();
												}
											}
										};
										
										new Thread(new Runnable() {
											@Override
											public void run() {
												try {
													String targetPath = edit.getText().toString();
													File dir = new File(targetPath);

													if(!dir.exists()) {
														dir.mkdir();
													}

													File cappFile = new File(dir.getPath() + "/" + appNames.get(p3) + ".apk");
													File appFile = new File(sourceDirs.get(p3));
													
													Files.copy(appFile.toPath(), cappFile.toPath());
													
//													FileOutputStream fos = new FileOutputStream(cappFile);
//													FileInputStream fis = new FileInputStream(appFile);
//													
//													int read;
//													while((read = fis.read()) != -1) {
//														fos.write(read);
//														
//													}
//													
//													fos.flush();
//													fos.close();
//													fos.close();
													
													Message msg = Message.obtain();
													msg.obj = "FINISH";
													
													handler.sendMessage(msg);
													
												} catch(Exception e) {
													e.printStackTrace();
												}
											}
										}).start();
									}
								})
								.show();
						}
					})
					.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface p1, int p2) {
							p1.dismiss();
						}
					})
					.show();
			}
		});

		return view;
	}

	private class BadAdapter extends BaseAdapter {
		private Context context;

		public BadAdapter(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			return infos.size();
		}

		@Override
		public Object getItem(int p1) {
			return null;
		}

		@Override
		public long getItemId(int p1) {
			return 0;
		}

		@Override
		public View getView(int p1, View p2, ViewGroup p3) {
			View view = null;

			if(p2 == null) {
				view = View.inflate(context, R.layout.item, null);
			} else {
				view = p2;
			}

			ImageView appIcon = view.findViewById(R.id.item_imageview);
			appIcon.setImageDrawable(drawables.get(p1));

			TextView appNameTextview = view.findViewById(R.id.item_name_textView);
			appNameTextview.setText(appNames.get(p1));

			TextView packageNameTextview = view.findViewById(R.id.item_package_name_textView);
			packageNameTextview.setText(packageNames.get(p1));

			return view;
		}
	}
}
